{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "OsXAs2gcIpbC"
      },
      "outputs": [],
      "source": [
        "# Copyright 2024 Google LLC\n",
        "#\n",
        "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "#     https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Bring-Your-Own-Autorater using `CustomMetric`"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "w-Edsbk7JRim"
      },
      "source": [
        "<table align=\"left\">\n",
        "  <td style=\"text-align: center\">\n",
        "    <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/generative-ai/blob/main/gemini/evaluation/evaltask_approach/bring_your_own_autorater_with_custom_metric.ipynb\">\n",
        "      <img width=\"32px\" src=\"https://www.gstatic.com/pantheon/images/bigquery/welcome_page/colab-logo.svg\" alt=\"Google Colaboratory logo\"><br> Open in Colab\n",
        "    </a>\n",
        "  </td>\n",
        "  <td style=\"text-align: center\">\n",
        "    <a href=\"https://console.cloud.google.com/vertex-ai/colab/import/https:%2F%2Fraw.githubusercontent.com%2FGoogleCloudPlatform%2Fgenerative-ai%2Fmain%2Fgemini%2Fevaluation%2Fevaltask_approach%2Fbring_your_own_autorater_with_custom_metric.ipynb\">\n",
        "      <img width=\"32px\" src=\"https://lh3.googleusercontent.com/JmcxdQi-qOpctIvWKgPtrzZdJJK-J3sWE1RsfjZNwshCFgE_9fULcNpuXYTilIR2hjwN\" alt=\"Google Cloud Colab Enterprise logo\"><br> Open in Colab Enterprise\n",
        "    </a>\n",
        "  </td>\n",
        "  <td style=\"text-align: center\">\n",
        "    <a href=\"https://console.cloud.google.com/vertex-ai/workbench/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/generative-ai/main/gemini/evaluation/evaltask_approach/bring_your_own_autorater_with_custom_metric.ipynb\">\n",
        "      <img src=\"https://www.gstatic.com/images/branding/gcpiconscolors/vertexai/v1/32px.svg\" alt=\"Vertex AI logo\"><br> Open in Vertex AI Workbench\n",
        "    </a>\n",
        "  </td>\n",
        "  <td style=\"text-align: center\">\n",
        "    <a href=\"https://github.com/GoogleCloudPlatform/generative-ai/blob/main/gemini/evaluation/evaltask_approach/bring_your_own_autorater_with_custom_metric.ipynb\">\n",
        "      <img width=\"32px\" src=\"https://raw.githubusercontent.com/primer/octicons/refs/heads/main/icons/mark-github-24.svg\" alt=\"GitHub logo\"><br> View on GitHub\n",
        "    </a>\n",
        "  </td>\n",
        "</table>\n",
        "\n",
        "<div style=\"clear: both;\"></div>\n",
        "\n",
        "<b>Share to:</b>\n",
        "\n",
        "<a href=\"https://www.linkedin.com/sharing/share-offsite/?url=https%3A//github.com/GoogleCloudPlatform/generative-ai/blob/main/gemini/evaluation/evaltask_approach/bring_your_own_autorater_with_custom_metric.ipynb\" target=\"_blank\">\n",
        "  <img width=\"20px\" src=\"https://upload.wikimedia.org/wikipedia/commons/8/81/LinkedIn_icon.svg\" alt=\"LinkedIn logo\">\n",
        "</a>\n",
        "\n",
        "<a href=\"https://bsky.app/intent/compose?text=https%3A//github.com/GoogleCloudPlatform/generative-ai/blob/main/gemini/evaluation/evaltask_approach/bring_your_own_autorater_with_custom_metric.ipynb\" target=\"_blank\">\n",
        "  <img width=\"20px\" src=\"https://upload.wikimedia.org/wikipedia/commons/7/7a/Bluesky_Logo.svg\" alt=\"Bluesky logo\">\n",
        "</a>\n",
        "\n",
        "<a href=\"https://twitter.com/intent/tweet?url=https%3A//github.com/GoogleCloudPlatform/generative-ai/blob/main/gemini/evaluation/evaltask_approach/bring_your_own_autorater_with_custom_metric.ipynb\" target=\"_blank\">\n",
        "  <img width=\"20px\" src=\"https://upload.wikimedia.org/wikipedia/commons/5/5a/X_icon_2.svg\" alt=\"X logo\">\n",
        "</a>\n",
        "\n",
        "<a href=\"https://reddit.com/submit?url=https%3A//github.com/GoogleCloudPlatform/generative-ai/blob/main/gemini/evaluation/evaltask_approach/bring_your_own_autorater_with_custom_metric.ipynb\" target=\"_blank\">\n",
        "  <img width=\"20px\" src=\"https://redditinc.com/hubfs/Reddit%20Inc/Brand/Reddit_Logo.png\" alt=\"Reddit logo\">\n",
        "</a>\n",
        "\n",
        "<a href=\"https://www.facebook.com/sharer/sharer.php?u=https%3A//github.com/GoogleCloudPlatform/generative-ai/blob/main/gemini/evaluation/evaltask_approach/bring_your_own_autorater_with_custom_metric.ipynb\" target=\"_blank\">\n",
        "  <img width=\"20px\" src=\"https://upload.wikimedia.org/wikipedia/commons/5/51/Facebook_f_logo_%282019%29.svg\" alt=\"Facebook logo\">\n",
        "</a>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "XYPDtg2hJRin"
      },
      "source": [
        "| | |\n",
        "|-|-|\n",
        "|Author(s) | [Jason Dai](https://github.com/jsondai) |"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "eujw2ajSJRin"
      },
      "source": [
        "## Overview\n",
        "\n",
        "Use the *Vertex AI Python SDK for Gen AI Evaluation Service* to evaluate generative AI models with your locally-defined `CustomMetric`, and use your own autorater model to perform model-based metric evaluation.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "w-OcPSC8_FUX"
      },
      "source": [
        "## Getting Started"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "-7Jso8-FO4N8"
      },
      "source": [
        "### Install Vertex AI Python SDK for Gen AI Evaluation Service"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "tUat7NRq5JDC"
      },
      "outputs": [],
      "source": [
        "%pip install --upgrade --user --quiet google-cloud-aiplatform[evaluation]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "iMbbf3YZJRio"
      },
      "source": [
        "### Restart runtime\n",
        "To use the newly installed packages in this Jupyter runtime, you must restart the runtime. You can do this by running the cell below, which restarts the current kernel.\n",
        "\n",
        "The restart might take a minute or longer. After it's restarted, continue to the next step."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "xABZ4JGtJRio"
      },
      "outputs": [],
      "source": [
        "import IPython\n",
        "\n",
        "app = IPython.Application.instance()\n",
        "app.kernel.do_shutdown(True)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vCaDF6wBJRio"
      },
      "source": [
        "<div class=\"alert alert-block alert-warning\">\n",
        "<b>⚠️ The kernel is going to restart. Wait until it's finished before continuing to the next step. ⚠️</b>\n",
        "</div>\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "HL1GhjLEJRip"
      },
      "source": [
        "### Authenticate your notebook environment (Colab only)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "metadata": {
        "id": "YUG3ZKzWJRip"
      },
      "outputs": [],
      "source": [
        "import sys\n",
        "\n",
        "if \"google.colab\" in sys.modules:\n",
        "    from google.colab import auth\n",
        "\n",
        "    auth.authenticate_user()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "T75ob0NjIPfa"
      },
      "source": [
        "### Set Google Cloud project information and initialize Vertex AI SDK"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "metadata": {
        "id": "36JfGpQgJRip"
      },
      "outputs": [],
      "source": [
        "PROJECT_ID = \"[your-project-id]\"  # @param {type:\"string\"}\n",
        "LOCATION = \"us-central1\"  # @param {type:\"string\"}\n",
        "\n",
        "if not PROJECT_ID or PROJECT_ID == \"[your-project-id]\":\n",
        "    raise ValueError(\"Please set your PROJECT_ID\")\n",
        "\n",
        "\n",
        "import vertexai\n",
        "\n",
        "vertexai.init(project=PROJECT_ID, location=LOCATION)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dvhI92xhQTzk"
      },
      "source": [
        "### Import libraries"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "metadata": {
        "id": "qP4ihOCkEBje"
      },
      "outputs": [],
      "source": [
        "import inspect\n",
        "import json\n",
        "\n",
        "import pandas as pd\n",
        "from vertexai.evaluation import CustomMetric, EvalTask\n",
        "from vertexai.generative_models import (\n",
        "    GenerationConfig,\n",
        "    GenerativeModel,\n",
        "    HarmBlockThreshold,\n",
        "    HarmCategory,\n",
        ")\n",
        "from vertexai.preview.evaluation import notebook_utils"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7Tf1bssiSBk7"
      },
      "source": [
        "## Using locally-defined `CustomMetric` class\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "U5P8TDQYHXZs"
      },
      "source": [
        "### Documentation\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "metadata": {
        "id": "y624wC75_xfy"
      },
      "outputs": [],
      "source": [
        "print(f\"{CustomMetric.__name__}:\\n{inspect.getdoc(CustomMetric)}\\n\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5ZSzjLI_rBSp"
      },
      "source": [
        "### Define a `CustomMetric` and \"Bring-Your-Own-Autorater\"\n",
        "\n",
        "Define a custom model-based metric and \"Bring-Your-Own-Autorater\". The custom model-based metric can contain multiple fields such as an autorater-graded score, explanations for the score, and more. The score field must match the name of the metric, other fields can be freeform strings."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "metadata": {
        "id": "IT2z2YztNKUs"
      },
      "outputs": [],
      "source": [
        "# Bring-Your-Own-Autorater and define your autorater inference function\n",
        "\n",
        "\n",
        "def get_autorater_response(metric_prompt: str) -> dict:\n",
        "    metric_response_schema = {\n",
        "        \"type\": \"OBJECT\",\n",
        "        \"properties\": {\n",
        "            \"score\": {\"type\": \"NUMBER\"},\n",
        "            \"explanation\": {\"type\": \"STRING\"},\n",
        "        },\n",
        "        \"required\": [\"score\", \"explanation\"],\n",
        "    }\n",
        "\n",
        "    autorater = GenerativeModel(\n",
        "        \"gemini-2.0-flash\",\n",
        "        generation_config=GenerationConfig(\n",
        "            response_mime_type=\"application/json\",\n",
        "            response_schema=metric_response_schema,\n",
        "        ),\n",
        "        safety_settings={\n",
        "            HarmCategory.HARM_CATEGORY_UNSPECIFIED: HarmBlockThreshold.BLOCK_NONE,\n",
        "            HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_NONE,\n",
        "            HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_NONE,\n",
        "            HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_NONE,\n",
        "            HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_NONE,\n",
        "        },\n",
        "    )\n",
        "\n",
        "    response = autorater.generate_content(metric_prompt)\n",
        "\n",
        "    response_json = {}\n",
        "\n",
        "    if response.candidates and len(response.candidates) > 0:\n",
        "        candidate = response.candidates[0]\n",
        "        if (\n",
        "            candidate.content\n",
        "            and candidate.content.parts\n",
        "            and len(candidate.content.parts) > 0\n",
        "        ):\n",
        "            part = candidate.content.parts[0]\n",
        "            if part.text:\n",
        "                response_json = json.loads(part.text)\n",
        "\n",
        "    return response_json"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 16,
      "metadata": {
        "id": "aT0uclHrSBlC"
      },
      "outputs": [],
      "source": [
        "# Define your metric computation function\n",
        "\n",
        "\n",
        "def linguistic_acceptability_fn(instance: dict) -> dict:\n",
        "    metric_prompt_template = \"\"\"\n",
        "# Instruction\n",
        "You are an expert evaluator. Your task is to evaluate the quality of the responses generated by AI models. We will provide you with the user prompt and an AI-generated responses.\n",
        "You should first read the user input carefully for analyzing the task, and then evaluate the quality of the responses based on the Criteria provided in the Evaluation section below.\n",
        "You will assign the response a rating following the Rating Rubric and Evaluation Steps. Give step by step explanations for your rating, and only choose ratings from the Rating Rubric.\n",
        "\n",
        "\n",
        "# Evaluation\n",
        "## Criteria\n",
        "Appropriate word choice: Words chosen are appropriate and purposeful given their relative context and positioning in the text. Vocabulary demonstrates prompt understanding.\n",
        "Proper Grammar: The language's grammar rules are correctly followed, including but not limited to sentence structures, verb tenses, subject-verb agreement, proper punctuation, and capitalization.\n",
        "Reference Alignment: The response is consistent and aligned with the reference.\n",
        "\n",
        "## Rating Rubric\n",
        "1: Poor: The writing is riddled with grammatical errors, uses highly inappropriate vocabulary, is completely unrelated to the reference.\n",
        "2: Unsatisfactory: The writing has significant grammatical errors, uses inappropriate vocabulary, deviates significantly from the reference.\n",
        "3: Satisfactory: The writing may have minor grammatical errors or use less-appropriate vocabulary, but it aligns reasonably well with the reference.\n",
        "4: Good: The writing is generally grammatically correct, uses appropriate vocabulary and aligns well with the reference.\n",
        "5: Excellent: The writing is grammatically correct, uses appropriate vocabulary and aligns perfectly with the reference.\n",
        "\n",
        "## Evaluation Steps\n",
        "Step 1: Assess the response in aspects of all criteria provided. Provide assessment according to each criterion.\n",
        "Step 2: Score based on the rating rubric. Give a brief rationale to explain your evaluation considering each individual criterion.\n",
        "\n",
        "\n",
        "# User Inputs and AI-generated Response\n",
        "## User Inputs\n",
        "### prompt\n",
        "{prompt}\n",
        "\n",
        "## AI-generated Response\n",
        "{response}\n",
        "\"\"\"\n",
        "    prompt = instance[\"prompt\"]\n",
        "    response = instance[\"response\"]\n",
        "\n",
        "    metric_prompt = metric_prompt_template.format(prompt=prompt, response=response)\n",
        "\n",
        "    response_dict = get_autorater_response(metric_prompt)\n",
        "\n",
        "    return {\n",
        "        \"linguistic_acceptability\": response_dict[\"score\"],\n",
        "        \"explanation\": response_dict[\"explanation\"],\n",
        "    }"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 18,
      "metadata": {
        "id": "BMrYN_OkSBlC"
      },
      "outputs": [],
      "source": [
        "# Define a CustomMetric\n",
        "linguistic_acceptability_metric = CustomMetric(\n",
        "    name=\"linguistic_acceptability\",\n",
        "    metric_function=linguistic_acceptability_fn,\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "JpdRqYlLq53t"
      },
      "source": [
        "### Run Evaluations with `CustomMetric`"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "6kQTJqIhSBlC"
      },
      "source": [
        "* The registered custom metrics are computed on the client side, without using Vertex Gen AI Evaluation Service APIs.\n",
        "\n",
        "* Mixing CustomMetric instances and other types of metrics is supported.\n",
        "\n",
        "* You can handle rate limiting of your own autorater with Eval SDK's [RateLimiter utils function](https://github.com/googleapis/python-aiplatform/blob/20f2cad85719b4793c2b77bf36c5a0d775b1a825/vertexai/evaluation/utils.py#L104) based on your autorater's capacity and QPS limit.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Qvt4ydMMQiMP"
      },
      "source": [
        "#### Define an evaluation dataset"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 21,
      "metadata": {
        "id": "hUGFuYawEJYX"
      },
      "outputs": [],
      "source": [
        "instruction = \"Summarize the following article\"\n",
        "\n",
        "context = [\n",
        "    \"To make a classic spaghetti carbonara, start by bringing a large pot of salted water to a boil. While the water is heating up, cook pancetta or guanciale in a skillet with olive oil over medium heat until it's crispy and golden brown. Once the pancetta is done, remove it from the skillet and set it aside. In the same skillet, whisk together eggs, grated Parmesan cheese, and black pepper to make the sauce. When the pasta is cooked al dente, drain it and immediately toss it in the skillet with the egg mixture, adding a splash of the pasta cooking water to create a creamy sauce.\",\n",
        "    \"Preparing a perfect risotto requires patience and attention to detail. Begin by heating butter in a large, heavy-bottomed pot over medium heat. Add finely chopped onions and minced garlic to the pot, and cook until they're soft and translucent, about 5 minutes. Next, add Arborio rice to the pot and cook, stirring constantly, until the grains are coated with the butter and begin to toast slightly. Pour in a splash of white wine and cook until it's absorbed. From there, gradually add hot chicken or vegetable broth to the rice, stirring frequently, until the risotto is creamy and the rice is tender with a slight bite.\",\n",
        "    \"For a flavorful grilled steak, start by choosing a well-marbled cut of beef like ribeye or New York strip. Season the steak generously with kosher salt and freshly ground black pepper on both sides, pressing the seasoning into the meat. Preheat a grill to high heat and brush the grates with oil to prevent sticking. Place the seasoned steak on the grill and cook for about 4-5 minutes on each side for medium-rare, or adjust the cooking time to your desired level of doneness. Let the steak rest for a few minutes before slicing against the grain and serving.\",\n",
        "    \"Creating a creamy homemade tomato soup is a comforting and simple process. Begin by heating olive oil in a large pot over medium heat. Add diced onions and minced garlic to the pot and cook until they're soft and fragrant. Next, add chopped fresh tomatoes, chicken or vegetable broth, and a sprig of fresh basil to the pot. Simmer the soup for about 20-30 minutes, or until the tomatoes are tender and falling apart. Remove the basil sprig and use an immersion blender to puree the soup until smooth. Season with salt and pepper to taste before serving.\",\n",
        "    \"To bake a decadent chocolate cake from scratch, start by preheating your oven to 350°F (175°C) and greasing and flouring two 9-inch round cake pans. In a large mixing bowl, cream together softened butter and granulated sugar until light and fluffy. Beat in eggs one at a time, making sure each egg is fully incorporated before adding the next. In a separate bowl, sift together all-purpose flour, cocoa powder, baking powder, baking soda, and salt. Divide the batter evenly between the prepared cake pans and bake for 25-30 minutes, or until a toothpick inserted into the center comes out clean.\",\n",
        "]\n",
        "\n",
        "reference = [\n",
        "    \"The process of making spaghetti carbonara involves boiling pasta, crisping pancetta or guanciale, whisking together eggs and Parmesan cheese, and tossing everything together to create a creamy sauce.\",\n",
        "    \"Preparing risotto entails sautéing onions and garlic, toasting Arborio rice, adding wine and broth gradually, and stirring until creamy and tender.\",\n",
        "    \"Grilling a flavorful steak involves seasoning generously, preheating the grill, cooking to desired doneness, and letting it rest before slicing.\",\n",
        "    \"Creating homemade tomato soup includes sautéing onions and garlic, simmering with tomatoes and broth, pureeing until smooth, and seasoning to taste.\",\n",
        "    \"Baking a decadent chocolate cake requires creaming butter and sugar, beating in eggs and alternating dry ingredients with buttermilk before baking until done.\",\n",
        "]\n",
        "\n",
        "\n",
        "eval_dataset = pd.DataFrame(\n",
        "    {\n",
        "        \"context\": context,\n",
        "        \"instruction\": [instruction] * len(context),\n",
        "        \"reference\": reference,\n",
        "    }\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "QHNcwnZ6Z65u"
      },
      "source": [
        "#### Define prompt templates to compare\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 22,
      "metadata": {
        "id": "T7nItAI3lBtz"
      },
      "outputs": [],
      "source": [
        "prompt_templates = [\n",
        "    \"Instruction: {instruction}. Article: {context}. Summary:\",\n",
        "    \"Article: {context}. Complete this task: {instruction}, in three sentence. Summary:\",\n",
        "    \"Goal: {instruction} and give me a TLDR. Here's a news article: {context}. Summary:\",\n",
        "]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9PRVpy2rqrIT"
      },
      "source": [
        "#### Define metrics\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 24,
      "metadata": {
        "id": "w4iU_mIhoY93"
      },
      "outputs": [],
      "source": [
        "metrics = [\"rouge_l_sum\", \"fluency\", \"coherence\", linguistic_acceptability_metric]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "U3r3NiKNqn3u"
      },
      "source": [
        "#### Define an EvalTask"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 27,
      "metadata": {
        "id": "zeVra-g1rAFV"
      },
      "outputs": [],
      "source": [
        "experiment_name = \"eval-custom-metric\"  # @param {type:\"string\"}\n",
        "\n",
        "eval_task = EvalTask(\n",
        "    dataset=eval_dataset,\n",
        "    metrics=metrics,\n",
        "    experiment=experiment_name,\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "bfGb1xggrGTO"
      },
      "source": [
        "#### Run an Evaluation"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "tiZuj8N8SBlC"
      },
      "outputs": [],
      "source": [
        "gemini_model = GenerativeModel(\n",
        "    \"gemini-2.0-flash\",\n",
        "    generation_config=GenerationConfig(\n",
        "        temperature=0.3,\n",
        "        top_k=1,\n",
        "    ),\n",
        "    safety_settings={\n",
        "        HarmCategory.HARM_CATEGORY_UNSPECIFIED: HarmBlockThreshold.BLOCK_NONE,\n",
        "        HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_NONE,\n",
        "        HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_NONE,\n",
        "        HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_NONE,\n",
        "        HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_NONE,\n",
        "    },\n",
        ")\n",
        "\n",
        "eval_results = []\n",
        "\n",
        "for i, prompt_template in enumerate(prompt_templates):\n",
        "    eval_result = eval_task.evaluate(\n",
        "        model=gemini_model,\n",
        "        prompt_template=prompt_template,\n",
        "    )\n",
        "\n",
        "    eval_results.append((f\"Prompt #{i}\", eval_result))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Rp0QfYV0srR5"
      },
      "source": [
        "#### Display Evaluation result and explanations"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "K8FkgEQ6SBlC"
      },
      "outputs": [],
      "source": [
        "for title, eval_result in eval_results:\n",
        "    notebook_utils.display_eval_result(title=title, eval_result=eval_result)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "_gzpbkwrsoCM"
      },
      "outputs": [],
      "source": [
        "for title, eval_result in eval_results:\n",
        "    notebook_utils.display_explanations(\n",
        "        eval_result, metrics=[\"linguistic_acceptability\"]\n",
        "    )"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "b42l5juJsyyY"
      },
      "source": [
        "#### Compare Eval Results"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 38,
      "metadata": {
        "id": "FA6rGbdpo3GE"
      },
      "outputs": [],
      "source": [
        "notebook_utils.display_radar_plot(\n",
        "    eval_results,\n",
        "    metrics=[\"fluency\", \"coherence\", \"linguistic_acceptability\"],\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 40,
      "metadata": {
        "id": "IFIBdtpgT0x3"
      },
      "outputs": [],
      "source": [
        "notebook_utils.display_bar_plot(eval_results, metrics=[\"rouge_l_sum\"])"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "HP0Zcm1yvh95"
      },
      "outputs": [],
      "source": [
        "eval_task.display_runs()"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [
        "bDmLyf-K5nRz"
      ],
      "name": "bring_your_own_autorater_with_custom_metric.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.12.8"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
